<?php

declare(strict_types=1);

namespace App\Controller\Admin\V1\Publics;

use App\Controller\Admin\V1\Controllers;
use App\Request\Publics\Uploadify as UploadifyRequest;
use Hyperf\Filesystem\FilesystemFactory;
use function Hyperf\Config\config;

class Uploadify extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = UploadifyRequest::class;

    /**
     * 多图上传
     * @param FilesystemFactory $factory
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \League\Flysystem\FilesystemException
     */
    public function images(FilesystemFactory $factory)
    {
        $files = $this->files('images');
        $qiniu = $factory->get('qiniu');
        $config = config('file.storage.qiniu');
        $path = [];
        foreach ($files as $file) {
            $key = date('Ymd').'/'.md5(microtime()).'.'.$file->getExtension();
            $stream = fopen($file->getRealPath(), 'r+');
            $qiniu->writeStream(
                $key,
                $stream
            );
            fclose($stream);
            $path[] = "{$config['domain']}/{$key}";
        }

        return success($path);
    }

    /**
     * 单图上传
     * @param FilesystemFactory $factory
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \League\Flysystem\FilesystemException
     */
    public function image(FilesystemFactory $factory)
    {
        $file = $this->files('image');
        $qiniu = $factory->get('qiniu');
        $config = config('file.storage.qiniu');
        $key = date('Ymd').'/'.md5(microtime()).'.'.$file->getExtension();
        $stream = fopen($file->getRealPath(), 'r+');
        $qiniu->writeStream(
            $key,
            $stream
        );
        fclose($stream);
        $path = "{$config['domain']}/{$key}";

        return success($path);
    }

    /**
     * 批量删除图片
     * @param FilesystemFactory $factory
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \League\Flysystem\FilesystemException
     */
    public function destroy(FilesystemFactory $factory)
    {
        $input = $this->input(['paths']);
        $qiniu = $factory->get('qiniu');
        foreach ($input['paths'] as $path) {
            $blah = parse_url($path);
            $uri = trim($blah['path'], '/');
            if ($qiniu->has($uri)) {
                $qiniu->delete($uri);
            }
        }

        return success();
    }
}
